package com.hd.trans.files.fragment;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.Group;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ConcatAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;
import com.hd.trans.R;
import com.hd.trans.db.bean.TransitionType;
import com.hd.trans.files.adapter.MediaListAdapter;
import com.hd.trans.files.adapter.VideoAdapter;
import com.hd.trans.files.bean.Audio;
import com.hd.trans.files.bean.Video;
import com.hd.trans.files.model.MediaListViewModel;
import com.hd.trans.files.model.PickingFileViewModel;
import com.hd.trans.utils.Constant;

import java.util.List;

/**
 * 媒体库
 */
public class MediaListFragment extends BaseFragment {

    public static final String ARG_TAB_INDEX = "ARG_TAB_INDEX";

    private RecyclerView mRecyclerView;
    private Group mEmptyView;

    private MediaListAdapter mAudioAdapter;
    private VideoAdapter mVideoAdapter;

    private PickingFileViewModel mPickingFileViewModel;
    private MediaListViewModel mMediaListViewModel;
    private TabLayout.Tab tab;
    private String title;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_media_list;
    }

    public static MediaListFragment newInstance(int tabIndex, int translationType) {
        MediaListFragment fragment = new MediaListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_TAB_INDEX, tabIndex);
        bundle.putInt(Constant.EXTRA_TRANSLATION_TYPE, translationType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        int tabIndex = getArguments() != null ? getArguments().getInt(ARG_TAB_INDEX) : 0;
        int translationType = getArguments() != null ? getArguments().getInt(Constant.EXTRA_TRANSLATION_TYPE) : TransitionType.DOCUMENT;
        mPickingFileViewModel = new ViewModelProvider(requireActivity()).get(PickingFileViewModel.class);

        mEmptyView = mRootView.findViewById(R.id.picking_file_empty_group);
        mRecyclerView = mRootView.findViewById(R.id.picking_file_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAudioAdapter = new MediaListAdapter(mPickingFileViewModel.getSelectedAudios());
        mVideoAdapter = new VideoAdapter();
        mRecyclerView.setAdapter(new ConcatAdapter(mAudioAdapter, mVideoAdapter));
        mRecyclerView.setItemAnimator(null);

        MediaListViewModel.MediaListViewModelFactory viewModelFactory = new MediaListViewModel
                .MediaListViewModelFactory(
                requireActivity().getApplication(),
                tabIndex,
                translationType
                );
        mMediaListViewModel = new ViewModelProvider(this, viewModelFactory).get(MediaListViewModel.class);
        getLifecycle().addObserver(mMediaListViewModel);

        initOnItemClick();

        // 根据关键词搜索
        mPickingFileViewModel.getSearchObserver().observe(
                getViewLifecycleOwner(),
                keyWord -> {
                    if (isResumed() || TextUtils.isEmpty(keyWord)) {
                        // 可见时才进行搜索
                        mMediaListViewModel.audioSearch(keyWord);
                    }
                }
        );

        // 排序修改
        mPickingFileViewModel.getFilesSortObserver().observe(
                getViewLifecycleOwner(), method -> {
                    /*if (mPickingFileViewModel.getFunction() == Configs.TAG_SDK_VIDEO_EXTRACTION_AUDIO) {
                    }*/
//                    mVideoAdapter.sort(method);
                    if (mAudioAdapter != null) mAudioAdapter.sort(method);
                }
        );

//        if (mPickingFileViewModel.getFunction() == Configs.TAG_SDK_VIDEO_EXTRACTION_AUDIO
//                && (tabIndex == 0 || tabIndex == 2)) {
//            initVideoObserver();
//        } else {
//            initAudioObserver();
//        }

        initAudioObserver();
    }

    private void initOnItemClick() {
//        if (mPickingFileViewModel.getFunction() == Configs.TAG_SDK_VIDEO_EXTRACTION_AUDIO) {
//            // 视频列表点击事件
            mVideoAdapter.setOnItemClickListener(
                    (viewId, video, position) -> mPickingFileViewModel.updateSelectedVideo(video)
            );
//        } else {
//            mAudioAdapter.setOnItemClickListener(
//                    (viewId, audio, position) -> mPickingFileViewModel.updateSelected(audio)
//            );
//        }
    }

    private void initAudioObserver() {

        // 加载音频数据
        mMediaListViewModel.getAudioDataObserver().observe(
                getViewLifecycleOwner(), this::showAudioData
        );

        // 更新选择音频状态
        mPickingFileViewModel.getSelectedAudiosObserver().observe(
                getViewLifecycleOwner(),
                audios -> mAudioAdapter.updateSelectedAudios(audios)
        );
    }

    private void initVideoObserver() {

        // 加载视频数据
        mMediaListViewModel.getVideoDataObserver().observe(
                getViewLifecycleOwner(), this::showVideoData
        );

        // 更新选择视频状态
        mPickingFileViewModel.getSelectedVideoObserver().observe(getViewLifecycleOwner(),
                videos -> mVideoAdapter.updateSelectedVideo(videos)
        );
    }

    private void showAudioData(List<Audio> audioData) {
        emptyData(audioData.isEmpty());
        mAudioAdapter.submitList(audioData);
        updateTab();
    }

    private void showVideoData(List<Video> videos) {
        emptyData(videos.isEmpty());
        mVideoAdapter.submitList(videos);
    }

    private void emptyData(boolean isEmpty) {
        if (isEmpty) {
            mEmptyView.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.INVISIBLE);
        } else {
            mEmptyView.setVisibility(View.INVISIBLE);
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void updateTab() {
        if (tab != null && title != null) {
            tab.setText(title + "(" + mAudioAdapter.getItemCount() + ")");
        }
    }

    public void setTab(TabLayout.Tab tab, String title) {
        this.tab = tab;
        this.title = title;
    }
}
